/*
 * @Author: zs.duan
 * @Date: 2023-04-05 14:48:45
 * @LastEditors: zs.duan
 * @LastEditTime: 2023-05-01 19:05:27
 * @FilePath: \serve\utils\Db.js
 */
const mysql = require('mysql');
const $dbConfig =  require('../config/config').sqlConfig;
const $errorCode = require('../config/config').errorCode;

// 创建连接池
const pool = mysql.createPool($dbConfig);

/**
 * 对query执行的结果自定义返回JSON结果
 * @param {*} res
 * @param {*} result
 * @param {*} resultJSON
 */
const responseDoReturn = (res, result, resultJSON) => {
    if (typeof result === 'undefined') {
        res.json($errorCode[10014]);
    } else {
        res.json(result);
    }
};

/**
 * 封装query之sql带占位符func
 * @param {string} sql sql语句
 * @param {any} [returnResult] 返回结果
 */
const query = (sql, returnResult) => {
    return new Promise((resolve, reject) => {
        if(!sql){
            console.warn("sql为空");
            resolve({
                ...$errorCode[10014],
                sql: sql
            });
            return ;
        }
        pool.getConnection(function(err, connection) {
            if(err){
                resolve({
                    ...$errorCode[10014],
                    sql: sql
                });
                return ;
            }
            connection.query(sql, returnResult, function(err, rows) {
                if (err) {
                    resolve({
                        ...$errorCode[10014],
                        sql: sql
                    })
                    console.log("失败的sql ==> ", sql);
                    if(returnResult){
                        returnResult.status(500)
                        return returnResult.json({
                            ...$errorCode[10015],
                        });
                    }
                }
                resolve(rows);
                //释放链接
                connection.release();
            });
        });
    }).catch(err => {
        console.log("sql执行err ==> ", err);
    })
}

/**
 * 封装query之sql带不占位符func
 * @param {string} sql sql语句
 * @param {Function} callback 查询成功后返回函数
 */
const queryArgs = (sql, callback) => {
    pool.getConnection(function(err, connection) {
        connection.query(sql, function(err, rows) {
            callback(err, rows);
            //释放链接
            connection.release();
        });
    });
}

module.exports = {
    query,
    queryArgs,
    responseDoReturn
}
